package com.lzl.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyHandler implements InvocationHandler {
    private Object object;
    private Object[] args;

    public ProxyHandler(Object object) {
        this.object = object;
    }

    public ProxyHandler(Object object, Object[] args) {
        this.object = object;
        this.args = args;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (this.args != null && this.args.length != 0) {
            args = this.args;
        }
        System.out.println("Before invoke " + method.getName());
        Object obj = method.invoke(object, args);
        System.out.println("After invoke " + method.getName());
        return obj;
    }

    public static void main(String[] args) {
        System.getProperties().setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

        HelloInterface hello = new Hello();

        InvocationHandler handler = new ProxyHandler(hello);

        HelloInterface proxyHello = (HelloInterface) Proxy.newProxyInstance(hello.getClass().getClassLoader(), hello.getClass().getInterfaces(), handler);

        proxyHello.sayHello();
        proxyHello.see();

        Object[] obj = new Object[1];
        obj[0] = "嘿嘿嘿11111";
        InvocationHandler handler1 = new ProxyHandler(hello, obj);
        HelloInterface proxyHello1 = (HelloInterface) Proxy.newProxyInstance(hello.getClass().getClassLoader(), hello.getClass().getInterfaces(), handler1);
        System.out.println(proxyHello.say("嘿嘿嘿"));
        System.out.println(proxyHello1.say("嘿嘿嘿"));
        Object[] obj1 = new Object[2];
        obj1[0] = "嘿嘿嘿22222";
        obj1[1] = 1;
        InvocationHandler handler2 = new ProxyHandler(hello, obj1);
        HelloInterface proxyHello2 = (HelloInterface) Proxy.newProxyInstance(hello.getClass().getClassLoader(), hello.getClass().getInterfaces(), handler2);
        System.out.println(proxyHello.say1("1",2));
        System.out.println(proxyHello2.say1("1",2));

    }
}
